package cn.turboinfo.dongying.api.provider.admin.component.init;

import cn.turboinfo.dongying.api.domain.admin.service.permission.PermissionService;
import cn.turboinfo.dongying.api.domain.common.service.role.RolePermissionService;
import cn.turboinfo.dongying.api.domain.common.service.role.RoleService;
import cn.turboinfo.dongying.api.domain.common.service.user.SysUserRoleService;
import cn.turboinfo.dongying.api.domain.common.service.user.SysUserService;
import cn.turboinfo.dongying.api.entity.admin.constant.AdminRoleConstants;
import cn.turboinfo.dongying.api.entity.admin.pojo.permission.Permission;
import cn.turboinfo.dongying.api.entity.admin.pojo.permission.PermissionCreator;
import cn.turboinfo.dongying.api.entity.admin.pojo.role.Role;
import cn.turboinfo.dongying.api.entity.admin.pojo.role.RoleCreator;
import cn.turboinfo.dongying.api.entity.admin.pojo.role.RolePermissionCreator;
import cn.turboinfo.dongying.api.entity.admin.pojo.user.SysUserRoleCreator;
import cn.turboinfo.dongying.api.entity.common.pojo.user.SysUser;
import cn.turboinfo.dongying.api.entity.common.pojo.user.SysUserCreator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.base.enums.EnableStatus;
import net.sunshow.toolkit.core.base.enums.YesNoStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Slf4j
@RequiredArgsConstructor
public class DefaultUserPermissionInitListener {

    @Value("${shiro.initAdminUsername:admin}")
    String initAdminUsername;

    @Value("${shiro.initAdminPassword:123456}")
    String initAdminPassword;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
        log.error("执行初始化管理员用户和角色权限");
        init();
    }

    private void init() {
        // 决定是否初始化用户
        if (StringUtils.isNotBlank(initAdminUsername) && StringUtils.isNotEmpty(initAdminPassword)) {
            Optional<SysUser> sysUserOptional = sysUserService.getByUsername(initAdminUsername);
            if (sysUserOptional.isPresent()) {
                return;
            }

            log.error("初始化默认管理员用户, initAdminUsername={}", initAdminPassword);

            // init user
            SysUser sysUser;
            {
                SysUserCreator.Builder builder = SysUserCreator.builder()
                        .withStatus(EnableStatus.ENABLED)
                        .withUsername(initAdminUsername);
                sysUser = sysUserService.save(builder.build(), initAdminPassword);
            }

            log.error("初始化默认管理员权限");

            // init sys permission
            Set<Long> permissionIdSet = new HashSet<>();
            {
                PermissionCreator.Builder parentBuilder = PermissionCreator.builder()
                        .withName("系统管理")
                        .withDescription("系统管理")
                        .withParentId(0L)
                        .withVisibleStatus(YesNoStatus.YES)
                        .withComponent("/sys")
                        .withResource("adminSys:null");
                Permission parent = permissionService.save(parentBuilder.build());
                permissionIdSet.add(parent.getId());

                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("权限管理")
                            .withDescription("权限管理")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.YES)
                            .withComponent("/permission/list")
                            .withResource("adminPermission:list");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("新增权限")
                            .withDescription("新增权限")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminPermission:create");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("编辑权限")
                            .withDescription("编辑权限")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminPermission:update");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("删除权限")
                            .withDescription("删除权限")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminPermission:delete");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }

                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("角色管理")
                            .withDescription("角色管理")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.YES)
                            .withComponent("/role/list")
                            .withResource("adminRole:list");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("新增角色")
                            .withDescription("新增角色")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminRole:create");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("编辑角色")
                            .withDescription("编辑角色")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminRole:update");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("删除角色")
                            .withDescription("删除角色")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminRole:delete");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("分配权限")
                            .withDescription("分配权限")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withComponent("/role/assignPermission")
                            .withResource("adminRole:assignPermission");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }

                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("系统用户管理")
                            .withDescription("系统用户管理")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.YES)
                            .withComponent("/user/list")
                            .withResource("adminSysUser:list");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("新增系统用户")
                            .withDescription("新增系统用户")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminSysUser:create");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("编辑系统用户")
                            .withDescription("编辑系统用户")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminSysUser:update");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("删除系统用户")
                            .withDescription("删除系统用户")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminSysUser:delete");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("分配角色")
                            .withDescription("分配角色")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminSysUser:assignRole");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
                {
                    PermissionCreator.Builder builder = PermissionCreator.builder()
                            .withName("重置密码")
                            .withDescription("重置密码")
                            .withParentId(parent.getId())
                            .withVisibleStatus(YesNoStatus.NO)
                            .withResource("adminSysUser:resetPassword");
                    Permission permission = permissionService.save(builder.build());
                    permissionIdSet.add(permission.getId());
                }
            }

            // init sys role
            Role role;
            {
                Optional<Role> optional = roleService.getByCode(AdminRoleConstants.ROLE_ADMIN);
                if (optional.isPresent()) {
                    role = optional.get();
                } else {
                    RoleCreator.Builder builder = RoleCreator.builder()
                            .withCode("admin")
                            .withName("管理员")
                            .withIsReserved(YesNoStatus.YES);
                    role = roleService.save(builder.build());
                }
            }

            // init sys role permission
            for (Long permissionId : permissionIdSet) {
                RolePermissionCreator.Builder builder = RolePermissionCreator.builder()
                        .withRoleId(role.getId())
                        .withPermissionId(permissionId);
                rolePermissionService.save(builder.build());
            }

            // init sys user role
            {
                SysUserRoleCreator.Builder builder = SysUserRoleCreator.builder()
                        .withSysUserId(sysUser.getId())
                        .withRoleId(role.getId());
                sysUserRoleService.save(builder.build());
            }
        }
    }
}
